home *** CD-ROM | disk | FTP | other *** search
/ Aminet 52 / Aminet 52 (2002)(GTI - Schatztruhe)[!][Dec 2002].iso / Aminet / dev / gg / ncurses-5.3.lha / ncurses-5.3 / progs / tic.c < prev    next >
C/C++ Source or Header  |  2002-10-24  |  30KB  |  1,146 lines

  1. /****************************************************************************
  2.  * Copyright (c) 1998-2001,2002 Free Software Foundation, Inc.              *
  3.  *                                                                          *
  4.  * Permission is hereby granted, free of charge, to any person obtaining a  *
  5.  * copy of this software and associated documentation files (the            *
  6.  * "Software"), to deal in the Software without restriction, including      *
  7.  * without limitation the rights to use, copy, modify, merge, publish,      *
  8.  * distribute, distribute with modifications, sublicense, and/or sell       *
  9.  * copies of the Software, and to permit persons to whom the Software is    *
  10.  * furnished to do so, subject to the following conditions:                 *
  11.  *                                                                          *
  12.  * The above copyright notice and this permission notice shall be included  *
  13.  * in all copies or substantial portions of the Software.                   *
  14.  *                                                                          *
  15.  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
  16.  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
  17.  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
  18.  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
  19.  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
  20.  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
  21.  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
  22.  *                                                                          *
  23.  * Except as contained in this notice, the name(s) of the above copyright   *
  24.  * holders shall not be used in advertising or otherwise to promote the     *
  25.  * sale, use or other dealings in this Software without prior written       *
  26.  * authorization.                                                           *
  27.  ****************************************************************************/
  28.  
  29. /****************************************************************************
  30.  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
  31.  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
  32.  *     and: Thomas E. Dickey 1996 on                                        *
  33.  ****************************************************************************/
  34.  
  35. /*
  36.  *    tic.c --- Main program for terminfo compiler
  37.  *            by Eric S. Raymond
  38.  *
  39.  */
  40.  
  41. #include <progs.priv.h>
  42. #include <sys/stat.h>
  43.  
  44. #include <dump_entry.h>
  45. #include <term_entry.h>
  46. #include <transform.h>
  47.  
  48. MODULE_ID("$Id: tic.c,v 1.102 2002/10/05 19:59:41 tom Exp $")
  49.  
  50. const char *_nc_progname = "tic";
  51.  
  52. static FILE *log_fp;
  53. static FILE *tmp_fp;
  54. static bool showsummary = FALSE;
  55. static const char *to_remove;
  56. static int tparm_errs;
  57.  
  58. static void (*save_check_termtype) (TERMTYPE *);
  59. static void check_termtype(TERMTYPE * tt);
  60.  
  61. static const char usage_string[] = "[-V] [-v[n]] [-e names] [-CILNRTcfrswx1] source-file\n";
  62.  
  63. static void
  64. cleanup(void)
  65. {
  66.     if (tmp_fp != 0)
  67.     fclose(tmp_fp);
  68.     if (to_remove != 0) {
  69. #if HAVE_REMOVE
  70.     remove(to_remove);
  71. #else
  72.     unlink(to_remove);
  73. #endif
  74.     }
  75. }
  76.  
  77. static void
  78. failed(const char *msg)
  79. {
  80.     perror(msg);
  81.     cleanup();
  82.     exit(EXIT_FAILURE);
  83. }
  84.  
  85. static void
  86. usage(void)
  87. {
  88.     static const char *const tbl[] =
  89.     {
  90.     "Options:",
  91.     "  -1         format translation output one capability per line",
  92. #if NCURSES_XNAMES
  93.     "  -a         retain commented-out capabilities (sets -x also)",
  94. #endif
  95.     "  -C         translate entries to termcap source form",
  96.     "  -c         check only, validate input without compiling or translating",
  97.     "  -e<names>  translate/compile only entries named by comma-separated list",
  98.     "  -f         format complex strings for readability",
  99.     "  -G         format %{number} to %'char'",
  100.     "  -g         format %'char' to %{number}",
  101.     "  -I         translate entries to terminfo source form",
  102.     "  -L         translate entries to full terminfo source form",
  103.     "  -N         disable smart defaults for source translation",
  104.     "  -o<dir>    set output directory for compiled entry writes",
  105.     "  -R<name>   restrict translation to given terminfo/termcap version",
  106.     "  -r         force resolution of all use entries in source translation",
  107.     "  -s         print summary statistics",
  108.     "  -T         remove size-restrictions on compiled description",
  109. #if NCURSES_XNAMES
  110.     "  -t         suppress commented-out capabilities",
  111. #endif
  112.     "  -V         print version",
  113.     "  -v[n]      set verbosity level",
  114.     "  -w[n]      set format width for translation output",
  115. #if NCURSES_XNAMES
  116.     "  -x         treat unknown capabilities as user-defined",
  117. #endif
  118.     "",
  119.     "Parameters:",
  120.     "  <file>     file to translate or compile"
  121.     };
  122.     size_t j;
  123.  
  124.     fprintf(stderr, "Usage: %s %s\n", _nc_progname, usage_string);
  125.     for (j = 0; j < SIZEOF(tbl); j++) {
  126.     fputs(tbl[j], stderr);
  127.     putc('\n', stderr);
  128.     }
  129.     exit(EXIT_FAILURE);
  130. }
  131.  
  132. #define L_BRACE '{'
  133. #define R_BRACE '}'
  134. #define S_QUOTE '\'';
  135.  
  136. static void
  137. write_it(ENTRY * ep)
  138. {
  139.     unsigned n;
  140.     int ch;
  141.     char *s, *d, *t;
  142.     char result[MAX_ENTRY_SIZE];
  143.  
  144.     /*
  145.      * Look for strings that contain %{number}, convert them to %'char',
  146.      * which is shorter and runs a little faster.
  147.      */
  148.     for (n = 0; n < STRCOUNT; n++) {
  149.     s = ep->tterm.Strings[n];
  150.     if (VALID_STRING(s)
  151.         && strchr(s, L_BRACE) != 0) {
  152.         d = result;
  153.         t = s;
  154.         while ((ch = *t++) != 0) {
  155.         *d++ = ch;
  156.         if (ch == '\\') {
  157.             *d++ = *t++;
  158.         } else if ((ch == '%')
  159.                && (*t == L_BRACE)) {
  160.             char *v = 0;
  161.             long value = strtol(t + 1, &v, 0);
  162.             if (v != 0
  163.             && *v == R_BRACE
  164.             && value > 0
  165.             && value != '\\'    /* FIXME */
  166.             && value < 127
  167.             && isprint((int) value)) {
  168.             *d++ = S_QUOTE;
  169.             *d++ = (int) value;
  170.             *d++ = S_QUOTE;
  171.             t = (v + 1);
  172.             }
  173.         }
  174.         }
  175.         *d = 0;
  176.         if (strlen(result) < strlen(s))
  177.         strcpy(s, result);
  178.     }
  179.     }
  180.  
  181.     _nc_set_type(_nc_first_name(ep->tterm.term_names));
  182.     _nc_curr_line = ep->startline;
  183.     _nc_write_entry(&ep->tterm);
  184. }
  185.  
  186. static bool
  187. immedhook(ENTRY * ep GCC_UNUSED)
  188. /* write out entries with no use capabilities immediately to save storage */
  189. {
  190. #if !HAVE_BIG_CORE
  191.     /*
  192.      * This is strictly a core-economy kluge.  The really clean way to handle
  193.      * compilation is to slurp the whole file into core and then do all the
  194.      * name-collision checks and entry writes in one swell foop.  But the
  195.      * terminfo master file is large enough that some core-poor systems swap
  196.      * like crazy when you compile it this way...there have been reports of
  197.      * this process taking *three hours*, rather than the twenty seconds or
  198.      * less typical on my development box.
  199.      *
  200.      * So.  This hook *immediately* writes out the referenced entry if it
  201.      * has no use capabilities.  The compiler main loop refrains from
  202.      * adding the entry to the in-core list when this hook fires.  If some
  203.      * other entry later needs to reference an entry that got written
  204.      * immediately, that's OK; the resolution code will fetch it off disk
  205.      * when it can't find it in core.
  206.      *
  207.      * Name collisions will still be detected, just not as cleanly.  The
  208.      * write_entry() code complains before overwriting an entry that
  209.      * postdates the time of tic's first call to write_entry().  Thus
  210.      * it will complain about overwriting entries newly made during the
  211.      * tic run, but not about overwriting ones that predate it.
  212.      *
  213.      * The reason this is a hook, and not in line with the rest of the
  214.      * compiler code, is that the support for termcap fallback cannot assume
  215.      * it has anywhere to spool out these entries!
  216.      *
  217.      * The _nc_set_type() call here requires a compensating one in
  218.      * _nc_parse_entry().
  219.      *
  220.      * If you define HAVE_BIG_CORE, you'll disable this kluge.  This will
  221.      * make tic a bit faster (because the resolution code won't have to do
  222.      * disk I/O nearly as often).
  223.      */
  224.     if (ep->nuses == 0) {
  225.     int oldline = _nc_curr_line;
  226.  
  227.     write_it(ep);
  228.     _nc_curr_line = oldline;
  229.     free(ep->tterm.str_table);
  230.     return (TRUE);
  231.     }
  232. #endif /* HAVE_BIG_CORE */
  233.     return (FALSE);
  234. }
  235.  
  236. static void
  237. put_translate(int c)
  238. /* emit a comment char, translating terminfo names to termcap names */
  239. {
  240.     static bool in_name = FALSE;
  241.     static size_t have, used;
  242.     static char *namebuf, *suffix;
  243.  
  244.     if (in_name) {
  245.     if (used + 1 >= have) {
  246.         have += 132;
  247.         namebuf = typeRealloc(char, have, namebuf);
  248.         suffix = typeRealloc(char, have, suffix);
  249.     }
  250.     if (c == '\n' || c == '@') {
  251.         namebuf[used++] = '\0';
  252.         (void) putchar('<');
  253.         (void) fputs(namebuf, stdout);
  254.         putchar(c);
  255.         in_name = FALSE;
  256.     } else if (c != '>') {
  257.         namebuf[used++] = c;
  258.     } else {        /* ah! candidate name! */
  259.         char *up;
  260.         NCURSES_CONST char *tp;
  261.  
  262.         namebuf[used++] = '\0';
  263.         in_name = FALSE;
  264.  
  265.         suffix[0] = '\0';
  266.         if ((up = strchr(namebuf, '#')) != 0
  267.         || (up = strchr(namebuf, '=')) != 0
  268.         || ((up = strchr(namebuf, '@')) != 0 && up[1] == '>')) {
  269.         (void) strcpy(suffix, up);
  270.         *up = '\0';
  271.         }
  272.  
  273.         if ((tp = nametrans(namebuf)) != 0) {
  274.         (void) putchar(':');
  275.         (void) fputs(tp, stdout);
  276.         (void) fputs(suffix, stdout);
  277.         (void) putchar(':');
  278.         } else {
  279.         /* couldn't find a translation, just dump the name */
  280.         (void) putchar('<');
  281.         (void) fputs(namebuf, stdout);
  282.         (void) fputs(suffix, stdout);
  283.         (void) putchar('>');
  284.         }
  285.     }
  286.     } else {
  287.     used = 0;
  288.     if (c == '<') {
  289.         in_name = TRUE;
  290.     } else {
  291.         putchar(c);
  292.     }
  293.     }
  294. }
  295.  
  296. /* Returns a string, stripped of leading/trailing whitespace */
  297. static char *
  298. stripped(char *src)
  299. {
  300.     while (isspace(UChar(*src)))
  301.     src++;
  302.     if (*src != '\0') {
  303.     char *dst = strcpy(malloc(strlen(src) + 1), src);
  304.     size_t len = strlen(dst);
  305.     while (--len != 0 && isspace(UChar(dst[len])))
  306.         dst[len] = '\0';
  307.     return dst;
  308.     }
  309.     return 0;
  310. }
  311.  
  312. static FILE *
  313. open_input(const char *filename)
  314. {
  315.     FILE *fp = fopen(filename, "r");
  316.     struct stat sb;
  317.  
  318.     if (fp == 0) {
  319.     fprintf(stderr, "%s: Can't open %s\n", _nc_progname, filename);
  320.     exit(EXIT_FAILURE);
  321.     }
  322.     if (fstat(fileno(fp), &sb) < 0
  323.     || (sb.st_mode & S_IFMT) != S_IFREG) {
  324.     fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
  325.     exit(EXIT_FAILURE);
  326.     }
  327.     return fp;
  328. }
  329.  
  330. /* Parse the "-e" option-value into a list of names */
  331. static const char **
  332. make_namelist(char *src)
  333. {
  334.     const char **dst = 0;
  335.  
  336.     char *s, *base;
  337.     unsigned pass, n, nn;
  338.     char buffer[BUFSIZ];
  339.  
  340.     if (src == 0) {
  341.     /* EMPTY */ ;
  342.     } else if (strchr(src, '/') != 0) {        /* a filename */
  343.     FILE *fp = open_input(src);
  344.  
  345.     for (pass = 1; pass <= 2; pass++) {
  346.         nn = 0;
  347.         while (fgets(buffer, sizeof(buffer), fp) != 0) {
  348.         if ((s = stripped(buffer)) != 0) {
  349.             if (dst != 0)
  350.             dst[nn] = s;
  351.             nn++;
  352.         }
  353.         }
  354.         if (pass == 1) {
  355.         dst = typeCalloc(const char *, nn + 1);
  356.         rewind(fp);
  357.         }
  358.     }
  359.     fclose(fp);
  360.     } else {            /* literal list of names */
  361.     for (pass = 1; pass <= 2; pass++) {
  362.         for (n = nn = 0, base = src;; n++) {
  363.         int mark = src[n];
  364.         if (mark == ',' || mark == '\0') {
  365.             if (pass == 1) {
  366.             nn++;
  367.             } else {
  368.             src[n] = '\0';
  369.             if ((s = stripped(base)) != 0)
  370.                 dst[nn++] = s;
  371.             base = &src[n + 1];
  372.             }
  373.         }
  374.         if (mark == '\0')
  375.             break;
  376.         }
  377.         if (pass == 1)
  378.         dst = typeCalloc(const char *, nn + 1);
  379.     }
  380.     }
  381.     if (showsummary) {
  382.     fprintf(log_fp, "Entries that will be compiled:\n");
  383.     for (n = 0; dst[n] != 0; n++)
  384.         fprintf(log_fp, "%d:%s\n", n + 1, dst[n]);
  385.     }
  386.     return dst;
  387. }
  388.  
  389. static bool
  390. matches(const char **needle, const char *haystack)
  391. /* does entry in needle list match |-separated field in haystack? */
  392. {
  393.     bool code = FALSE;
  394.     size_t n;
  395.  
  396.     if (needle != 0) {
  397.     for (n = 0; needle[n] != 0; n++) {
  398.         if (_nc_name_match(haystack, needle[n], "|")) {
  399.         code = TRUE;
  400.         break;
  401.         }
  402.     }
  403.     } else
  404.     code = TRUE;
  405.     return (code);
  406. }
  407.  
  408. static FILE *
  409. open_tempfile(char *name)
  410. {
  411.     FILE *result = 0;
  412. #if HAVE_MKSTEMP
  413.     int fd = mkstemp(name);
  414.     if (fd >= 0)
  415.     result = fdopen(fd, "w");
  416. #else
  417.     if (tmpnam(name) != 0)
  418.     result = fopen(name, "w");
  419. #endif
  420.     return result;
  421. }
  422.  
  423. int
  424. main(int argc, char *argv[])
  425. {
  426.     char my_tmpname[PATH_MAX];
  427.     int v_opt = -1, debug_level;
  428.     int smart_defaults = TRUE;
  429.     char *termcap;
  430.     ENTRY *qp;
  431.  
  432.     int this_opt, last_opt = '?';
  433.  
  434.     int outform = F_TERMINFO;    /* output format */
  435.     int sortmode = S_TERMINFO;    /* sort_mode */
  436.  
  437.     int width = 60;
  438.     bool formatted = FALSE;    /* reformat complex strings? */
  439.     int numbers = 0;        /* format "%'char'" to/from "%{number}" */
  440.     bool infodump = FALSE;    /* running as captoinfo? */
  441.     bool capdump = FALSE;    /* running as infotocap? */
  442.     bool forceresolve = FALSE;    /* force resolution */
  443.     bool limited = TRUE;
  444.     char *tversion = (char *) NULL;
  445.     const char *source_file = "terminfo";
  446.     const char **namelst = 0;
  447.     char *outdir = (char *) NULL;
  448.     bool check_only = FALSE;
  449.     bool suppress_untranslatable = FALSE;
  450.  
  451.     log_fp = stderr;
  452.  
  453.     _nc_progname = _nc_rootname(argv[0]);
  454.  
  455.     if ((infodump = (strcmp(_nc_progname, PROG_CAPTOINFO) == 0)) != FALSE) {
  456.     outform = F_TERMINFO;
  457.     sortmode = S_TERMINFO;
  458.     }
  459.     if ((capdump = (strcmp(_nc_progname, PROG_INFOTOCAP) == 0)) != FALSE) {
  460.     outform = F_TERMCAP;
  461.     sortmode = S_TERMCAP;
  462.     }
  463. #if NCURSES_XNAMES
  464.     use_extended_names(FALSE);
  465. #endif
  466.  
  467.     /*
  468.      * Processing arguments is a little complicated, since someone made a
  469.      * design decision to allow the numeric values for -w, -v options to
  470.      * be optional.
  471.      */
  472.     while ((this_opt = getopt(argc, argv,
  473.                   "0123456789CILNR:TVace:fGgo:rstvwx")) != EOF) {
  474.     if (isdigit(this_opt)) {
  475.         switch (last_opt) {
  476.         case 'v':
  477.         v_opt = (v_opt * 10) + (this_opt - '0');
  478.         break;
  479.         case 'w':
  480.         width = (width * 10) + (this_opt - '0');
  481.         break;
  482.         default:
  483.         if (this_opt != '1')
  484.             usage();
  485.         last_opt = this_opt;
  486.         width = 0;
  487.         }
  488.         continue;
  489.     }
  490.     switch (this_opt) {
  491.     case 'C':
  492.         capdump = TRUE;
  493.         outform = F_TERMCAP;
  494.         sortmode = S_TERMCAP;
  495.         break;
  496.     case 'I':
  497.         infodump = TRUE;
  498.         outform = F_TERMINFO;
  499.         sortmode = S_TERMINFO;
  500.         break;
  501.     case 'L':
  502.         infodump = TRUE;
  503.         outform = F_VARIABLE;
  504.         sortmode = S_VARIABLE;
  505.         break;
  506.     case 'N':
  507.         smart_defaults = FALSE;
  508.         break;
  509.     case 'R':
  510.         tversion = optarg;
  511.         break;
  512.     case 'T':
  513.         limited = FALSE;
  514.         break;
  515.     case 'V':
  516.         puts(curses_version());
  517.         return EXIT_SUCCESS;
  518.     case 'c':
  519.         check_only = TRUE;
  520.         break;
  521.     case 'e':
  522.         namelst = make_namelist(optarg);
  523.         break;
  524.     case 'f':
  525.         formatted = TRUE;
  526.         break;
  527.     case 'G':
  528.         numbers = 1;
  529.         break;
  530.     case 'g':
  531.         numbers = -1;
  532.         break;
  533.     case 'o':
  534.         outdir = optarg;
  535.         break;
  536.     case 'r':
  537.         forceresolve = TRUE;
  538.         break;
  539.     case 's':
  540.         showsummary = TRUE;
  541.         break;
  542.     case 'v':
  543.         v_opt = 0;
  544.         break;
  545.     case 'w':
  546.         width = 0;
  547.         break;
  548. #if NCURSES_XNAMES
  549.     case 't':
  550.         _nc_disable_period = FALSE;
  551.         suppress_untranslatable = TRUE;
  552.         break;
  553.     case 'a':
  554.         _nc_disable_period = TRUE;
  555.         /* FALLTHRU */
  556.     case 'x':
  557.         use_extended_names(TRUE);
  558.         break;
  559. #endif
  560.     default:
  561.         usage();
  562.     }
  563.     last_opt = this_opt;
  564.     }
  565.  
  566.     debug_level = (v_opt > 0) ? v_opt : (v_opt == 0);
  567.     set_trace_level(debug_level);
  568.  
  569.     if (_nc_tracing) {
  570.     save_check_termtype = _nc_check_termtype;
  571.     _nc_check_termtype = check_termtype;
  572.     }
  573. #if !HAVE_BIG_CORE
  574.     /*
  575.      * Aaargh! immedhook seriously hoses us!
  576.      *
  577.      * One problem with immedhook is it means we can't do -e.  Problem
  578.      * is that we can't guarantee that for each terminal listed, all the
  579.      * terminals it depends on will have been kept in core for reference
  580.      * resolution -- in fact it's certain the primitive types at the end
  581.      * of reference chains *won't* be in core unless they were explicitly
  582.      * in the select list themselves.
  583.      */
  584.     if (namelst && (!infodump && !capdump)) {
  585.     (void) fprintf(stderr,
  586.                "Sorry, -e can't be used without -I or -C\n");
  587.     cleanup();
  588.     return EXIT_FAILURE;
  589.     }
  590. #endif /* HAVE_BIG_CORE */
  591.  
  592.     if (optind < argc) {
  593.     source_file = argv[optind++];
  594.     if (optind < argc) {
  595.         fprintf(stderr,
  596.             "%s: Too many file names.  Usage:\n\t%s %s",
  597.             _nc_progname,
  598.             _nc_progname,
  599.             usage_string);
  600.         return EXIT_FAILURE;
  601.     }
  602.     } else {
  603.     if (infodump == TRUE) {
  604.         /* captoinfo's no-argument case */
  605.         source_file = "/etc/termcap";
  606.         if ((termcap = getenv("TERMCAP")) != 0
  607.         && (namelst = make_namelist(getenv("TERM"))) != 0) {
  608.         if (access(termcap, F_OK) == 0) {
  609.             /* file exists */
  610.             source_file = termcap;
  611.         } else if ((tmp_fp = open_tempfile(strcpy(my_tmpname,
  612.                               "/tmp/XXXXXX")))
  613.                != 0) {
  614.             source_file = my_tmpname;
  615.             fprintf(tmp_fp, "%s\n", termcap);
  616.             fclose(tmp_fp);
  617.             tmp_fp = open_input(source_file);
  618.             to_remove = source_file;
  619.         } else {
  620.             failed("tmpnam");
  621.         }
  622.         }
  623.     } else {
  624.         /* tic */
  625.         fprintf(stderr,
  626.             "%s: File name needed.  Usage:\n\t%s %s",
  627.             _nc_progname,
  628.             _nc_progname,
  629.             usage_string);
  630.         cleanup();
  631.         return EXIT_FAILURE;
  632.     }
  633.     }
  634.  
  635.     if (tmp_fp == 0)
  636.     tmp_fp = open_input(source_file);
  637.  
  638.     if (infodump)
  639.     dump_init(tversion,
  640.           smart_defaults
  641.           ? outform
  642.           : F_LITERAL,
  643.           sortmode, width, debug_level, formatted);
  644.     else if (capdump)
  645.     dump_init(tversion,
  646.           outform,
  647.           sortmode, width, debug_level, FALSE);
  648.  
  649.     /* parse entries out of the source file */
  650.     _nc_set_source(source_file);
  651. #if !HAVE_BIG_CORE
  652.     if (!(check_only || infodump || capdump))
  653.     _nc_set_writedir(outdir);
  654. #endif /* HAVE_BIG_CORE */
  655.     _nc_read_entry_source(tmp_fp, (char *) NULL,
  656.               !smart_defaults, FALSE,
  657.               (check_only || infodump || capdump) ? NULLHOOK : immedhook);
  658.  
  659.     /* do use resolution */
  660.     if (check_only || (!infodump && !capdump) || forceresolve) {
  661.     if (!_nc_resolve_uses(TRUE) && !check_only) {
  662.         cleanup();
  663.         return EXIT_FAILURE;
  664.     }
  665.     }
  666.  
  667.     /* length check */
  668.     if (check_only && (capdump || infodump)) {
  669.     for_entry_list(qp) {
  670.         if (matches(namelst, qp->tterm.term_names)) {
  671.         int len = fmt_entry(&qp->tterm, NULL, FALSE, TRUE, infodump, numbers);
  672.  
  673.         if (len > (infodump ? MAX_TERMINFO_LENGTH : MAX_TERMCAP_LENGTH))
  674.             (void) fprintf(stderr,
  675.                    "warning: resolved %s entry is %d bytes long\n",
  676.                    _nc_first_name(qp->tterm.term_names),
  677.                    len);
  678.         }
  679.     }
  680.     }
  681.  
  682.     /* write or dump all entries */
  683.     if (!check_only) {
  684.     if (!infodump && !capdump) {
  685.         _nc_set_writedir(outdir);
  686.         for_entry_list(qp) {
  687.         if (matches(namelst, qp->tterm.term_names))
  688.             write_it(qp);
  689.         }
  690.     } else {
  691.         /* this is in case infotocap() generates warnings */
  692.         _nc_curr_col = _nc_curr_line = -1;
  693.  
  694.         for_entry_list(qp) {
  695.         if (matches(namelst, qp->tterm.term_names)) {
  696.             int j = qp->cend - qp->cstart;
  697.             int len = 0;
  698.  
  699.             /* this is in case infotocap() generates warnings */
  700.             _nc_set_type(_nc_first_name(qp->tterm.term_names));
  701.  
  702.             (void) fseek(tmp_fp, qp->cstart, SEEK_SET);
  703.             while (j--) {
  704.             if (infodump)
  705.                 (void) putchar(fgetc(tmp_fp));
  706.             else
  707.                 put_translate(fgetc(tmp_fp));
  708.             }
  709.  
  710.             len = dump_entry(&qp->tterm, suppress_untranslatable,
  711.                      limited, 0, numbers, NULL);
  712.             for (j = 0; j < qp->nuses; j++)
  713.             len += dump_uses(qp->uses[j].name, !capdump);
  714.             (void) putchar('\n');
  715.             if (debug_level != 0 && !limited)
  716.             printf("# length=%d\n", len);
  717.         }
  718.         }
  719.         if (!namelst && _nc_tail) {
  720.         int c, oldc = '\0';
  721.         bool in_comment = FALSE;
  722.         bool trailing_comment = FALSE;
  723.  
  724.         (void) fseek(tmp_fp, _nc_tail->cend, SEEK_SET);
  725.         while ((c = fgetc(tmp_fp)) != EOF) {
  726.             if (oldc == '\n') {
  727.             if (c == '#') {
  728.                 trailing_comment = TRUE;
  729.                 in_comment = TRUE;
  730.             } else {
  731.                 in_comment = FALSE;
  732.             }
  733.             }
  734.             if (trailing_comment
  735.             && (in_comment || (oldc == '\n' && c == '\n')))
  736.             putchar(c);
  737.             oldc = c;
  738.         }
  739.         }
  740.     }
  741.     }
  742.  
  743.     /* Show the directory into which entries were written, and the total
  744.      * number of entries
  745.      */
  746.     if (showsummary
  747.     && (!(check_only || infodump || capdump))) {
  748.     int total = _nc_tic_written();
  749.     if (total != 0)
  750.         fprintf(log_fp, "%d entries written to %s\n",
  751.             total,
  752.             _nc_tic_dir((char *) 0));
  753.     else
  754.         fprintf(log_fp, "No entries written\n");
  755.     }
  756.     cleanup();
  757.     return (EXIT_SUCCESS);
  758. }
  759.  
  760. /*
  761.  * This bit of legerdemain turns all the terminfo variable names into
  762.  * references to locations in the arrays Booleans, Numbers, and Strings ---
  763.  * precisely what's needed (see comp_parse.c).
  764.  */
  765.  
  766. TERMINAL *cur_term;        /* tweak to avoid linking lib_cur_term.c */
  767.  
  768. #undef CUR
  769. #define CUR tp->
  770.  
  771. /*
  772.  * Returns the expected number of parameters for the given capability.
  773.  */
  774. static int
  775. expected_params(const char *name)
  776. {
  777.     /* *INDENT-OFF* */
  778.     static const struct {
  779.     const char *name;
  780.     int count;
  781.     } table[] = {
  782.     { "S0",            1 },    /* 'screen' extension */
  783.     { "birep",        2 },
  784.     { "chr",        1 },
  785.     { "colornm",        1 },
  786.     { "cpi",        1 },
  787.     { "csnm",        1 },
  788.     { "csr",        2 },
  789.     { "cub",        1 },
  790.     { "cud",        1 },
  791.     { "cuf",        1 },
  792.     { "cup",        2 },
  793.     { "cuu",        1 },
  794.     { "cvr",        1 },
  795.     { "cwin",        5 },
  796.     { "dch",        1 },
  797.     { "defc",        3 },
  798.     { "dial",        1 },
  799.     { "dispc",        1 },
  800.     { "dl",            1 },
  801.     { "ech",        1 },
  802.     { "getm",        1 },
  803.     { "hpa",        1 },
  804.     { "ich",        1 },
  805.     { "il",            1 },
  806.     { "indn",        1 },
  807.     { "initc",        4 },
  808.     { "initp",        7 },
  809.     { "lpi",        1 },
  810.     { "mc5p",        1 },
  811.     { "mrcup",        2 },
  812.     { "mvpa",        1 },
  813.     { "pfkey",        2 },
  814.     { "pfloc",        2 },
  815.     { "pfx",        2 },
  816.     { "pfxl",        3 },
  817.     { "pln",        2 },
  818.     { "qdial",        1 },
  819.     { "rcsd",        1 },
  820.     { "rep",        2 },
  821.     { "rin",        1 },
  822.     { "sclk",        3 },
  823.     { "scp",        1 },
  824.     { "scs",        1 },
  825.     { "scsd",        2 },
  826.     { "setab",        1 },
  827.     { "setaf",        1 },
  828.     { "setb",        1 },
  829.     { "setcolor",        1 },
  830.     { "setf",        1 },
  831.     { "sgr",        9 },
  832.     { "sgr1",        6 },
  833.     { "slength",        1 },
  834.     { "slines",        1 },
  835.     { "smgbp",        1 },    /* 2 if smgtp is not given */
  836.     { "smglp",        1 },
  837.     { "smglr",        2 },
  838.     { "smgrp",        1 },
  839.     { "smgtb",        2 },
  840.     { "smgtp",        1 },
  841.     { "tsl",        1 },
  842.     { "u6",            -1 },
  843.     { "vpa",        1 },
  844.     { "wind",        4 },
  845.     { "wingo",        1 },
  846.     };
  847.     /* *INDENT-ON* */
  848.  
  849.     unsigned n;
  850.     int result = 0;        /* function-keys, etc., use none */
  851.  
  852.     for (n = 0; n < SIZEOF(table); n++) {
  853.     if (!strcmp(name, table[n].name)) {
  854.         result = table[n].count;
  855.         break;
  856.     }
  857.     }
  858.  
  859.     return result;
  860. }
  861.  
  862. /*
  863.  * Make a quick sanity check for the parameters which are used in the given
  864.  * strings.  If there are no "%p" tokens, then there should be no other "%"
  865.  * markers.
  866.  */
  867. static void
  868. check_params(TERMTYPE * tp, const char *name, char *value)
  869. {
  870.     int expected = expected_params(name);
  871.     int actual = 0;
  872.     int n;
  873.     bool params[10];
  874.     char *s = value;
  875.  
  876. #ifdef set_top_margin_parm
  877.     if (!strcmp(name, "smgbp")
  878.     && set_top_margin_parm == 0)
  879.     expected = 2;
  880. #endif
  881.  
  882.     for (n = 0; n < 10; n++)
  883.     params[n] = FALSE;
  884.  
  885.     while (*s != 0) {
  886.     if (*s == '%') {
  887.         if (*++s == '\0') {
  888.         _nc_warning("expected character after %% in %s", name);
  889.         break;
  890.         } else if (*s == 'p') {
  891.         if (*++s == '\0' || !isdigit((int) *s)) {
  892.             _nc_warning("expected digit after %%p in %s", name);
  893.             return;
  894.         } else {
  895.             n = (*s - '0');
  896.             if (n > actual)
  897.             actual = n;
  898.             params[n] = TRUE;
  899.         }
  900.         }
  901.     }
  902.     s++;
  903.     }
  904.  
  905.     if (params[0]) {
  906.     _nc_warning("%s refers to parameter 0 (%%p0), which is not allowed", name);
  907.     }
  908.     if (value == set_attributes || expected < 0) {
  909.     ;
  910.     } else if (expected != actual) {
  911.     _nc_warning("%s uses %d parameters, expected %d", name,
  912.             actual, expected);
  913.     for (n = 1; n < actual; n++) {
  914.         if (!params[n])
  915.         _nc_warning("%s omits parameter %d", name, n);
  916.     }
  917.     }
  918. }
  919.  
  920. static char *
  921. skip_delay(char *s)
  922. {
  923.     while (*s == '/' || isdigit(UChar(*s)))
  924.     ++s;
  925.     return s;
  926. }
  927.  
  928. /*
  929.  * An sgr string may contain several settings other than the one we're
  930.  * interested in, essentially sgr0 + rmacs + whatever.  As long as the
  931.  * "whatever" is contained in the sgr string, that is close enough for our
  932.  * sanity check.
  933.  */
  934. static bool
  935. similar_sgr(int num, char *a, char *b)
  936. {
  937.     static const char *names[] =
  938.     {
  939.     "none"
  940.     ,"standout"
  941.     ,"underline"
  942.     ,"reverse"
  943.     ,"blink"
  944.     ,"dim"
  945.     ,"bold"
  946.     ,"invis"
  947.     ,"protect"
  948.     ,"altcharset"
  949.     };
  950.     char *base_a = a;
  951.     char *base_b = b;
  952.     int delaying = 0;
  953.  
  954.     while (*b != 0) {
  955.     while (*a != *b) {
  956.         if (*a == 0) {
  957.         if (b[0] == '$'
  958.             && b[1] == '<') {
  959.             _nc_warning("Did not find delay %s", _nc_visbuf(b));
  960.         } else {
  961.             _nc_warning("checking sgr(%s) %s\n\tcompare to %s\n\tunmatched %s",
  962.                 names[num], _nc_visbuf2(1, base_a),
  963.                 _nc_visbuf2(2, base_b),
  964.                 _nc_visbuf2(3, b));
  965.         }
  966.         return FALSE;
  967.         } else if (delaying) {
  968.         a = skip_delay(a);
  969.         b = skip_delay(b);
  970.         } else {
  971.         a++;
  972.         }
  973.     }
  974.     switch (*a) {
  975.     case '$':
  976.         if (delaying == 0)
  977.         delaying = 1;
  978.         break;
  979.     case '<':
  980.         if (delaying == 1)
  981.         delaying = 2;
  982.         break;
  983.     default:
  984.         delaying = 0;
  985.         break;
  986.     }
  987.     a++;
  988.     b++;
  989.     }
  990.     return TRUE;
  991. }
  992.  
  993. static void
  994. check_sgr(TERMTYPE * tp, char *zero, int num, char *cap, const char *name)
  995. {
  996.     char *test = tparm(set_attributes,
  997.                num == 1,
  998.                num == 2,
  999.                num == 3,
  1000.                num == 4,
  1001.                num == 5,
  1002.                num == 6,
  1003.                num == 7,
  1004.                num == 8,
  1005.                num == 9);
  1006.     tparm_errs += _nc_tparm_err;
  1007.     if (test != 0) {
  1008.     if (PRESENT(cap)) {
  1009.         if (!similar_sgr(num, test, cap)) {
  1010.         _nc_warning("%s differs from sgr(%d)\n\t%s=%s\n\tsgr(%d)=%s",
  1011.                 name, num,
  1012.                 name, _nc_visbuf2(1, cap),
  1013.                 num, _nc_visbuf2(2, test));
  1014.         }
  1015.     } else if (strcmp(test, zero)) {
  1016.         _nc_warning("sgr(%d) present, but not %s", num, name);
  1017.     }
  1018.     } else if (PRESENT(cap)) {
  1019.     _nc_warning("sgr(%d) missing, but %s present", num, name);
  1020.     }
  1021. }
  1022.  
  1023. #define CHECK_SGR(num,name) check_sgr(tp, zero, num, name, #name)
  1024.  
  1025. /* other sanity-checks (things that we don't want in the normal
  1026.  * logic that reads a terminfo entry)
  1027.  */
  1028. static void
  1029. check_termtype(TERMTYPE * tp)
  1030. {
  1031.     bool conflict = FALSE;
  1032.     unsigned j, k;
  1033.     char fkeys[STRCOUNT];
  1034.  
  1035.     /*
  1036.      * A terminal entry may contain more than one keycode assigned to
  1037.      * a given string (e.g., KEY_END and KEY_LL).  But curses will only
  1038.      * return one (the last one assigned).
  1039.      */
  1040.     memset(fkeys, 0, sizeof(fkeys));
  1041.     for (j = 0; _nc_tinfo_fkeys[j].code; j++) {
  1042.     char *a = tp->Strings[_nc_tinfo_fkeys[j].offset];
  1043.     bool first = TRUE;
  1044.     if (!VALID_STRING(a))
  1045.         continue;
  1046.     for (k = j + 1; _nc_tinfo_fkeys[k].code; k++) {
  1047.         char *b = tp->Strings[_nc_tinfo_fkeys[k].offset];
  1048.         if (!VALID_STRING(b)
  1049.         || fkeys[k])
  1050.         continue;
  1051.         if (!strcmp(a, b)) {
  1052.         fkeys[j] = 1;
  1053.         fkeys[k] = 1;
  1054.         if (first) {
  1055.             if (!conflict) {
  1056.             _nc_warning("Conflicting key definitions (using the last)");
  1057.             conflict = TRUE;
  1058.             }
  1059.             fprintf(stderr, "... %s is the same as %s",
  1060.                 keyname(_nc_tinfo_fkeys[j].code),
  1061.                 keyname(_nc_tinfo_fkeys[k].code));
  1062.             first = FALSE;
  1063.         } else {
  1064.             fprintf(stderr, ", %s",
  1065.                 keyname(_nc_tinfo_fkeys[k].code));
  1066.         }
  1067.         }
  1068.     }
  1069.     if (!first)
  1070.         fprintf(stderr, "\n");
  1071.     }
  1072.  
  1073.     for (j = 0; j < NUM_STRINGS(tp); j++) {
  1074.     char *a = tp->Strings[j];
  1075.     if (VALID_STRING(a))
  1076.         check_params(tp, ExtStrname(tp, j, strnames), a);
  1077.     }
  1078.  
  1079.     /*
  1080.      * Quick check for color.  We could also check if the ANSI versus
  1081.      * non-ANSI strings are misused.
  1082.      */
  1083.     if ((max_colors > 0) != (max_pairs > 0)
  1084.     || ((max_colors > max_pairs) && (initialize_pair == 0)))
  1085.     _nc_warning("inconsistent values for max_colors (%d) and max_pairs (%d)",
  1086.             max_colors, max_pairs);
  1087.  
  1088.     PAIRED(set_foreground, set_background);
  1089.     PAIRED(set_a_foreground, set_a_background);
  1090.  
  1091.     /*
  1092.      * These may be mismatched because the terminal description relies on
  1093.      * restoring the cursor visibility by resetting it.
  1094.      */
  1095.     ANDMISSING(cursor_invisible, cursor_normal);
  1096.     ANDMISSING(cursor_visible, cursor_normal);
  1097.  
  1098.     if (PRESENT(cursor_visible) && PRESENT(cursor_normal)
  1099.     && !strcmp(cursor_visible, cursor_normal))
  1100.     _nc_warning("cursor_visible is same as cursor_normal");
  1101.  
  1102.     /*
  1103.      * From XSI & O'Reilly, we gather that sc/rc are required if csr is
  1104.      * given, because the cursor position after the scrolling operation is
  1105.      * performed is undefined.
  1106.      */
  1107.     ANDMISSING(change_scroll_region, save_cursor);
  1108.     ANDMISSING(change_scroll_region, restore_cursor);
  1109.  
  1110.     tparm_errs = 0;
  1111.     if (PRESENT(set_attributes)) {
  1112.     char *zero = tparm(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1113.  
  1114.     zero = strdup(zero);
  1115.     CHECK_SGR(1, enter_standout_mode);
  1116.     CHECK_SGR(2, enter_underline_mode);
  1117.     CHECK_SGR(3, enter_reverse_mode);
  1118.     CHECK_SGR(4, enter_blink_mode);
  1119.     CHECK_SGR(5, enter_dim_mode);
  1120.     CHECK_SGR(6, enter_bold_mode);
  1121.     CHECK_SGR(7, enter_secure_mode);
  1122.     CHECK_SGR(8, enter_protected_mode);
  1123.     CHECK_SGR(9, enter_alt_charset_mode);
  1124.     free(zero);
  1125.     if (tparm_errs)
  1126.         _nc_warning("stack error in sgr string");
  1127.     }
  1128.  
  1129.     /*
  1130.      * Some standard applications (e.g., vi) and some non-curses
  1131.      * applications (e.g., jove) get confused if we have both ich1 and
  1132.      * smir/rmir.  Let's be nice and warn about that, too, even though
  1133.      * ncurses handles it.
  1134.      */
  1135.     if ((PRESENT(enter_insert_mode) || PRESENT(exit_insert_mode))
  1136.     && PRESENT(parm_ich)) {
  1137.     _nc_warning("non-curses applications may be confused by ich1 with smir/rmir");
  1138.     }
  1139.  
  1140.     /*
  1141.      * Finally, do the non-verbose checks
  1142.      */
  1143.     if (save_check_termtype != 0)
  1144.     save_check_termtype(tp);
  1145. }
  1146.